package constant.milk.cashbook.sms;

import java.util.ArrayList;

import constant.milk.cashbook.bean.SmsReceiverData;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver
{
//	private static final String ACTION ="android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent)
	{
//		if (!intent.getAction().equals(ACTION))
//		{
//			return;
//		}
		
		Bundle bundle = intent.getExtras();
		
		if (bundle == null) 
		{
			return;
		}
		
		Object[] pdusObj = (Object[]) bundle.get("pdus");
		
		if (pdusObj == null) 
		{
			return;
		}
		
		SmsMessage[] smsMessages = new SmsMessage[pdusObj.length];
		
		ArrayList<SmsReceiverData> list = new ArrayList<SmsReceiverData>();
		
		for (int i = 0; i < pdusObj.length; i++) 
		{
			smsMessages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

			String address = smsMessages[i].getDisplayOriginatingAddress();
			
			String body = smsMessages[i].getDisplayMessageBody();
			
			if (address == null || address.length() == 0 || address.equals(""))
			{
				continue;
			}
			
			if (body == null || body.length() == 0 || body.equals(""))
			{
				continue;
			}
			
			SmsReceiverData data = new SmsReceiverData();
			
			data.setAddress(address);
			data.setBody(body);
			
			list.add(data);
		}
		
		if (list.size() > 0)
		{
			Intent inputIntent = new Intent(context, SmsService.class);
			inputIntent.putExtra(SmsService.SMS_ARRAY, list);
	        context.startService(inputIntent);
		}
	}
}
